/* Load and store settings. */

module settings;

private {
	import common;
	import main;
}

char[][] mods;
char[] modName;
const char[] modFileName = "mods.ini";

private {
	const char[] settingsFileName = "settings.ini";

	const char[][] defaultMods = ["westernq3", "baseq3", "wop", "InstaUnlagged"];

	private Ini settingsIni;

	struct Setting {
		char[] name;
		char[] value;
	}
	Setting[] defaults = [{"gamePath", r"C:\Program Files\Quake III Arena\quake3.exe"},
	                      {"windowSize", "800x568"},
	                      {"windowMaximized", "false"},
	                      {"minimizeOnGameLaunch", "true"},
	                     ];
}

void loadModFile()
{
	if (!exists(modFileName))
		write(modFileName, std.string.join(defaultMods, std.string.newline) ~ std.string.newline);

	mods = splitlines(cast(char[])read(modFileName));
	if (!modName)
		modName = mods[0];
}


void loadSettings()
{
	settingsIni = new Ini(settingsFileName);
	IniSection sec;

	if (settingsIni.sections.length > 0) {
		sec = settingsIni.sections[0];
	}
	else {
		sec = settingsIni.addSection("");
	}

	// merge the loaded settings with the defaults
	foreach(Setting s; defaults) {
		if (sec.getValue(s.name) is null)
			sec.setValue(s.name, s.value);
	}

	loadModFile();
}


void saveSettings()
{
	if (!mainWindow.getMaximized() && !mainWindow.getMinimized())
		setSetting("windowSize", std.string.format(mainWindow.getSize().x, "x", mainWindow.getSize().y));

	setSetting("windowMaximized", mainWindow.getMaximized() ? "true" : "false");

	if (settingsIni.modified)
		settingsIni.save();
}


char[] getSetting(char[] key)
{
	assert(settingsIni && settingsIni.sections.length > 0);
	IniSection sec = settingsIni.sections[0];

	assert(sec[key]);
	return sec[key];
}


void setSetting(char[] key, char[] value)
{
	assert(settingsIni && settingsIni.sections.length > 0);
	IniSection sec = settingsIni.sections[0];

	assert(sec[key]);
	sec[key] = value;
}
